class_name StateMachine
extends Node2D

var owner_parent = null
var states: Dictionary = {}
var current_state: StateBase = null
var current_state_name: String = ""


func _ready() -> void:
	owner_parent = get_parent()
	
	states = {}
	for child in get_children():
		states[child.name.to_lower()] = child
		child.state_machine = self
		

func _process(delta: float) -> void:
	if not current_state: return
	
	current_state.on_process(delta, owner_parent)
	

func _physics_process(delta: float) -> void:
	if not current_state: return
	
	current_state.on_physics_process(delta, owner_parent)
	

func transition(target_state_name: String):
	target_state_name = target_state_name.to_lower()
	
	#if  target_state_name == current_state_name: 
		#print("cant transition 2 same state")
		#return
	
	if not states.get(target_state_name):
		print("no such target state", target_state_name)
		return
	
	if current_state:
		current_state.on_exit(owner_parent)
		current_state = null
		current_state_name = ""
	
	current_state = states.get(target_state_name) as StateBase
	current_state_name = target_state_name
	current_state.on_enter(owner_parent)
	
		
